package org.ktx.osr.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.ktx.osr.data.SettingsRepository
import org.ktx.osr.ui.AppSettings

class SettingsViewModel(application: Application) : AndroidViewModel(application) {
    
    private val settingsRepository = SettingsRepository(application)
    
    // 设置状态的StateFlow
    private val _settings = MutableStateFlow(AppSettings())
    val settings: StateFlow<AppSettings> = _settings.asStateFlow()
    
    // 加载状态
    private val _isLoading = MutableStateFlow(true)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    init {
        loadSettings()
    }
    
    private fun loadSettings() {
        viewModelScope.launch {
            settingsRepository.settings.collect { settings ->
                _settings.value = settings
                _isLoading.value = false
            }
        }
    }
    
    fun updateResolution(resolution: String) {
        viewModelScope.launch {
            settingsRepository.updateResolution(resolution)
        }
    }
    
    fun updateFrameRate(frameRate: String) {
        viewModelScope.launch {
            settingsRepository.updateFrameRate(frameRate)
        }
    }
    
    fun updateVideoFormat(videoFormat: String) {
        viewModelScope.launch {
            settingsRepository.updateVideoFormat(videoFormat)
        }
    }
    
    fun updateIncludeSystemSound(include: Boolean) {
        viewModelScope.launch {
            settingsRepository.updateIncludeSystemSound(include)
        }
    }
    
    fun updateIncludeMicrophone(include: Boolean) {
        viewModelScope.launch {
            settingsRepository.updateIncludeMicrophone(include)
        }
    }
    
    fun updateIncludeCamera(include: Boolean) {
        viewModelScope.launch {
            settingsRepository.updateIncludeCamera(include)
        }
    }
    
    fun updateSaveLocation(location: String) {
        viewModelScope.launch {
            settingsRepository.updateSaveLocation(location)
        }
    }
    
    fun updateSettings(settings: AppSettings) {
        viewModelScope.launch {
            settingsRepository.updateSettings(settings)
            _settings.value = settings
        }
    }
    
    // 获取设置仓库实例，供Service使用
    fun getSettingsRepository(): SettingsRepository = settingsRepository
}
